package com.winton.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.winton.model.S_ITEM;
import com.winton.model.S_USER;
import com.winton.service.ItemService;

@Controller
@RequestMapping("/item")
public class ItemController {
	
	@Autowired
	ItemService itemService;
	
	
	@ResponseBody
	@RequestMapping("/inserOrUpdatetItem")
	public String inserOrUpdatetItem(HttpServletRequest request, HttpSession session,S_ITEM item,Model model) {
		S_USER u = (S_USER) session.getAttribute("user");
		item.setUserid(u.getId());
		String obj = (item.getId()!=0) ? itemService.updateItem(item) : itemService.addItem(item);
		 obj = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
		return obj;
	}
	
	@RequestMapping("/queryItemList")
	public ModelAndView queryItemList(@RequestParam(value="pageon",defaultValue="1")int pageon,
			HttpServletRequest request, HttpSession session,S_ITEM item,ModelAndView mv,Model model) {
		model.addAttribute("item", item);		
		mv.addAllObjects(itemService.queryItemList(item,pageon));
		mv.setViewName("item/system-category");
		
		return mv;
	}
	
	@RequestMapping("/itemAddPage")
	public String itemAddPage(HttpServletRequest request, HttpSession session,Model model) {
		
		model.addAttribute("levelItem",itemService.queryLevelItem()); 
										
		return "item/system-category-add";
	}
	
	@RequestMapping("/findItemById")
	public String findItemById(HttpServletRequest request, HttpSession session,S_ITEM item,Model model) {
		
		model.addAttribute("item",itemService.findItemById(item.getId())); 
		model.addAttribute("levelItem",itemService.queryLevelItem()); 								
		return "item/system-category-update";
	}
	
	@RequestMapping("/updateItem")
	public String updateItem(HttpServletRequest request, HttpSession session,S_ITEM item,Model model) {
		
										
		return "";
	}
	
	@ResponseBody
	@RequestMapping("/deleteItemById")
	public String deleteItemByUserId(HttpServletRequest request, HttpSession session,S_ITEM item,Model model) {
		List<S_ITEM> list = itemService.findItemByPid(item.getId());
		
		String obj="";
		if(list!=null && list.size()>0) {
			obj="删除失败,请先删除下级栏目！";
		}else {
			obj = itemService.deleteItemById(item.getId())+"";
		}		
		obj = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);	
		return obj;
	}

}
